<?php

namespace App\Models\Bureau;

use App\Models\Shop\WxShopContact;
use App\Models\User\WxUser;
use App\Models\WxChat;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

class WxClub extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'wx_club';

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {

        });

        static::created(function ($model) {
            WxUser::where('id', $model->user_id)->update(['club_id'=>$model->id]);
            self::sync_contact($model);
            GatewayUtils::success(GatewayUtils::uid2client_id($model->user_id), 12);
        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();

            // 对比更新前后的字段
            foreach ($changes as $key => $value) {
                if($key == 'status') {
                    $originalValue = $original[$key];

                    if($originalValue == 1){
                        if($model->status == 1){

                        }else{
                            UserUtils::add_user_notice(9001, $model->user_id,'俱乐部状态审核中','您的创建的「'.$model->name.'」状态变更为审核中，等待管理员的审核',100);
                        }
                    }else{
                        if($model->status == 1){
                            $updates = [];
                            if(!_empty_($model->avatar_tmp)){
                                $updates['avatar'] = $model->avatar_tmp;
                                $updates['avatar_tmp'] = null;
                            }
                            if(!_empty_($model->name_tmp)){
                                $updates['name'] = $model->name_tmp;
                                $updates['name_tmp'] = null;
                            }
                            if(!_empty_($model->intro_tmp)){
                                $updates['intro'] = $model->intro_tmp;
                                $updates['intro_tmp'] = null;
                            }
                            if(!_empty_($model->club_background_maps_tmp)){
                                $updates['club_background_maps'] = $model->club_background_maps_tmp;
                                $updates['club_background_maps_tmp'] = null;
                            }
                            if($updates){
                                WxClub::where('id', $model->id)->update($updates);
                            }
                            UserUtils::add_user_notice(9001, $model->user_id,'俱乐部创建审核通过','您的创建的「'.$model->name.'」已经审核通过，快去发布您的第一个组局活动吧',100);
                            GatewayUtils::success(GatewayUtils::uid2client_id($model->user_id), 12);
                        }else{

                        }
                    }

                }
            }
            self::sync_contact($model);
        });

        static::deleted(function ($model) {
            WxUser::where('id', $model->user_id)->update(['club_id'=>null]);
            WxShopContact::where('club_id', $model->id)->forceDelete();
            WxChat::where('expand_type', 110)->where('expand_id', $model->id)->forceDelete();
            GatewayUtils::success(GatewayUtils::uid2client_id($model->user_id), 12);
        });
    }

    private static function sync_contact(&$model){
        // 更新shop_contact
        $attributes = [
            'club_id' => $model->id,
        ];
        $values = [
            'user_id' => $model->user_id,
            'name' => $model->name,
            'phone' => _get_origin_attribute('wx_user', [['id', '=', $model->user_id]], 'phone'),
            'longitude' => $model->longitude,
            'latitude' => $model->latitude,
            'address_name' => $model->address_name,
            'address_detail' => $model->address_detailed,
        ];
        $shop_contact = WxShopContact::withTrashed()->firstOrNew($attributes);
        if ($shop_contact->trashed()) {
            $shop_contact->restore();
        }
        $shop_contact->fill($values)->save();
    }

    public function ower()
    {
        return $this->hasOne(WxUser::class, 'id', 'user_id');
    }

    public function getIpAddressAttribute()
    {
        if($this->country) {
            $show = Settings::get('app_ip_club_show', 3);
            if ($show == 0) {
                return '';
            } else if ($show == 1) {
                return $this->country;
            } else if ($show == 2) {
                return $this->province;
            } else if ($show == 3) {
                return $this->city;
            } else if ($show == 4) {
                return $this->district;
            }
        }
        return '';
    }

    public function getNameAttribute($value)
    {
        if($this->status === 0){
            global $__MINI_GLOBAL_SCENE__,$__MINI_GLOBAL_REQUEST_ENV__,$__MINI_GLOBAL_CURRENT_USER_ID__;
            if($__MINI_GLOBAL_SCENE__ == 154){
                if(!_empty_($this->name_tmp)){
                    if($__MINI_GLOBAL_CURRENT_USER_ID__ == $this->user_id){
                        return $this->name_tmp;
                    }
                }
            }
        }
        return $value;
    }

    public function getAvatarAttribute($value)
    {
        if($this->status === 0){
            global $__MINI_GLOBAL_SCENE__,$__MINI_GLOBAL_REQUEST_ENV__,$__MINI_GLOBAL_CURRENT_USER_ID__;
            if($__MINI_GLOBAL_SCENE__ == 154){
                if(!_empty_($this->avatar_tmp)){
                    if($__MINI_GLOBAL_CURRENT_USER_ID__ == $this->user_id){
                        return $this->avatar_tmp;
                    }
                }
            }
            if($__MINI_GLOBAL_REQUEST_ENV__ == 'web'){
                if(!_empty_($this->avatar_tmp)){
                    return $this->avatar_tmp;
                }
            }
        }
        if(_empty_($value)){
            return Settings::get('app_bureau_club_default_avatar', '');
        }
        return $value;
    }

    public function getIntroAttribute($value)
    {
        if($this->status === 0){
            global $__MINI_GLOBAL_SCENE__,$__MINI_GLOBAL_REQUEST_ENV__,$__MINI_GLOBAL_CURRENT_USER_ID__;
            if($__MINI_GLOBAL_SCENE__ == 154){
                if(!_empty_($this->intro_tmp)){
                    if($__MINI_GLOBAL_CURRENT_USER_ID__ == $this->user_id){
                        return $this->intro_tmp;
                    }
                }
            }
            if($__MINI_GLOBAL_REQUEST_ENV__ == 'web'){
                if(!_empty_($this->intro_tmp)){
                    return $value . "\n➡️\n" .$this->intro_tmp;
                }
            }
        }
        return $value;
    }

    public function getClubBackgroundMapsAttribute($value)
    {
        if($this->status === 0){
            global $__MINI_GLOBAL_SCENE__, $__MINI_GLOBAL_REQUEST_ENV__, $__MINI_GLOBAL_CURRENT_USER_ID__;
            if($__MINI_GLOBAL_SCENE__ == 154){
                if(!_empty_($this->club_background_maps_tmp)){
                    if($__MINI_GLOBAL_CURRENT_USER_ID__ == $this->user_id) {
                        return $this->club_background_maps_tmp;
                    }
                }
            }
            if($__MINI_GLOBAL_REQUEST_ENV__ == 'web'){
                if(!_empty_($this->club_background_maps_tmp)){
                    return $this->club_background_maps_tmp;
                }
            }
        }
        if(_empty_($value)){
            return Settings::get('app_bureau_club_background_maps', '');
        }
        return $value;
    }

}
